package com.jumi.microservice.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.jumi.microservice.config.AliPayConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author scw
 * @date 2020/11/3
 */
@RestController
@RequestMapping("/pay/return")
public class PayReturnController {
    @Resource
    private AliPayConfig aliPayConfig;

    /**
     * 支付宝H5
     * 支付结果同步回调
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/aliH5", method = RequestMethod.GET)
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        request.setCharacterEncoding("utf-8");//乱码解决，这段代码在出现乱码时使用
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String str : requestParams.keySet()) {
            String name = str;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //付邮领【自定义参数不参与验签】
            if (!"flyFlag".equals(name)) {
                params.put(name, valueStr);
            }
        }
        //付邮领【自定义参数】
        String flyFlag = request.getParameter("flyFlag");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getPublicKey(), "utf-8", "RSA2");//调用SDK验证签名
        String redirectUrl;
        if (signVerified) {
            //重定向 跳转至支付成功后的页面
            redirectUrl = aliPayConfig.getReturnSuccessUrl();
            if (!"".equals(flyFlag) && null != flyFlag) {
                redirectUrl = redirectUrl + "/" + flyFlag;
            }
        } else {
            //重定向 跳转到支付失败后的页面
            redirectUrl = aliPayConfig.getReturnFailUrl();
        }
        response.sendRedirect(redirectUrl);
    }
}
